﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;

namespace csvformater.config
{
    /// <summary>
    /// this is a configure class for oprating the configure file
    /// </summary>
    public static class Configure
    {
        public static string ConfigPath;

        public static string ConfigDir;

        private static XmlDocument _xmlDocument;

        private static XPathNavigator _xPathNavigator;
        
        /// <summary>
        /// write data into confiure file, return false if it is not sucessed
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        static Configure()
        {
            try
            {
                ConfigPath = System.Configuration.ConfigurationSettings.AppSettings["configPath"];
                ConfigDir = Path.GetDirectoryName(ConfigPath);
                _xmlDocument = new XmlDocument();
                _xmlDocument.Load(ConfigPath);
                _xPathNavigator = _xmlDocument.CreateNavigator();
            }
            catch (Exception)
            {

                throw new Exception("App file is not configure propertly");
            }
                
        }

        public static bool Write(string key = null , string value = null)
        {
            if(key != null)
            {
                
            }
            return false;
        }
    
        /// <summary>
        /// expression is using xpath standard
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static string Read(string expression = null)
        {
            if (expression != null)
            {
                switch (expression)
                {
                    case "ConfigPath":
                        return ConfigPath;
                    case "ConfigDir":
                        return ConfigDir;
                    default:
                        var nodeIterator = _xPathNavigator.Select(expression);
                        while (nodeIterator.MoveNext())
                        {
                            if (nodeIterator.Current != null) return  (nodeIterator.Current.Value) as string;
                        }
                        break;
                }
            }
            return null;
        }
    }
}
